/*
 * Project Name: cms_manager
 * File Name: RoleMenuService.java
 * Copyright: ZKTeco Corporation 2015
 * Description: TODO 请在此处添加对本文件的描述
 * Creator: Administrator
 * Create Date: 2015年3月10日 下午3:40:11
 */
package com.shishuo.cms.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.shishuo.cms.dao.UserRoleMenuDao;
import com.shishuo.cms.entity.UserMenuEntity;
import com.shishuo.cms.entity.UserRoleMenuEntity;

/**
 */
@Service
public class UserRoleMenuService extends BaseService<UserRoleMenuEntity, Long>
{
	private UserRoleMenuDao userRoleMenuDao;

	@Autowired
	public void setUserRoleMenuDao(UserRoleMenuDao userRoleMenuDao)
	{
		setBaseDao(userRoleMenuDao);
		this.userRoleMenuDao = userRoleMenuDao;
	}

	/**
	 * 根据roleId获取所拥有的所有菜单
	 * 
	 * @param roleId
	 * @return
	 */
	@Cacheable(value = "menuListByRoleId", key = "'getMenuListByRoleId_'+#roleId")
	public List<UserRoleMenuEntity> getListByRoleId(long roleId)
	{
		return userRoleMenuDao.getListByRoleId(roleId);
	}

	/**
	 * 配置角色与菜单关系到数据库中，并更新到内存中
	 * 
	 * @param selectMenuIds
	 * @param roleId
	 * @throws Exception
	 */
	@Transactional
	@CacheEvict(value = "menuListByRoleId", allEntries = true)
	public void configRoleMenu(long[] selectMenuIds, long roleId) throws Exception
	{
		userRoleMenuDao.deleteByRoleId(roleId);
		if (null != selectMenuIds)
		{
			for (int i = 0; i < selectMenuIds.length; i++)
			{
				UserRoleMenuEntity roleMenuEntity = new UserRoleMenuEntity();
				roleMenuEntity.setMenuId(selectMenuIds[i]);
				roleMenuEntity.setRoleId(roleId);
				this.insert(roleMenuEntity);
			}
		}
	}

	/**
	 * 判断是否此url在菜单中存在
	 * @param roleId
	 * @param url
	 * @return
	 */
	public boolean hasAuthByRoleIdAndUrl(long roleId, String menuUrl)
	{
		UserRoleMenuEntity roleMenuEntityCondition=new UserRoleMenuEntity();
		roleMenuEntityCondition.setRoleId(roleId);
		UserMenuEntity menu=new UserMenuEntity();
		menu.setMenuUrl(menuUrl);
		roleMenuEntityCondition.setMenu(menu);
		UserRoleMenuEntity roleMenuEntity=userRoleMenuDao.getRoleMenuByRoleIdAndUrl(roleMenuEntityCondition);
		return roleMenuEntity==null?false:true;
	}

}
